<?php
/**
 * Created by PhpStorm.
 * User: Administratorjing
 * Date: 2018/6/28/028
 * Time: 22:43
 */

namespace app\api\service;


use app\api\model\User;
use app\lib\exception\OrderException;
use app\lib\exception\UserException;

class DeliveryMessage extends WxMessage
{
    //小程序模板消息id号
   const DELIVERY_MSG_ID = 'YgYIUfQK00gn2BNqKF5vlVJ6NH0o9sEJm036MIuhXCI';
   public function sendDeliveryMessage($order, $tplJumpPage = '')
   {
       if(!$order){
           throw new OrderException();
       }
       $this->tplID = self::DELIVERY_MSG_ID;
       $this->formID = $order->prepay_id;
       $this->page =  $tplJumpPage;
       $this->prepareMessageData($order);
       $this->emphasisKeyWord='keyword2.DATA';
       return parent::sendMessage($this->getUserOpenID($order->user_id));
   }


    /**
     * 自定义模板
     * @param $order
     */
   private function prepareMessageData($order)
   {
       $dt = new \DateTime();
       $data = [
         'keyword1' => [
             'value' => '顺丰速递',
         ],
           'keyword2' => [
               'value' => $order->snap_name,
               'color' => '#27408B'
           ],
           'keyword3' => [
               'value' => $dt->format("Y-m-d H:i"),
           ],
       ];
       $this->$data = $data;
   }

    /**
     * 获得用户的openid
     * @param $uid
     * @return mixed
     * @throws UserException
     */
   private function getUserOpenID($uid)
   {
       $user = User::get($uid);
       if(!$user){
           throw new UserException();
       }
       return $user->openid;
   }
}